/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.settings;

import com.intellij.lang.ant.config.AntBuildFile;
import com.intellij.lang.ant.config.AntBuildListener;
import com.intellij.lang.ant.config.AntBuildTarget;
import com.intellij.lang.ant.config.AntConfiguration;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;

public class SaveWorkspaceAction extends AnAction {
    private Logger logger = Logger.getInstance(getClass().getName());

    public void actionPerformed(AnActionEvent e) {
        Project project = DataKeys.PROJECT.getData(e.getDataContext());
        logger.info("project = " + project);
        AntConfiguration antConfiguration = AntConfiguration.getInstance(project);
        AntBuildFile[] antBuildFiles = antConfiguration.getBuildFiles();
        for (int i = 0; i < antBuildFiles.length; i++) {
            AntBuildFile antBuildFile = antBuildFiles[i];
            logger.info("AntBuildFile: " + antBuildFile);
            AntBuildTarget buildTarget = antBuildFile.getModel().findTarget("save-workspace");
            logger.info("Build target = " + buildTarget);
            if (buildTarget != null) {
                final SettingsChecker checker = SettingsChecker.getInstance(project);
                checker.manualChange();
                project.save();
                buildTarget.run(new DataContext() {
                    @Nullable
                    public Object getData(@NonNls String dataId) {
                        logger.info("getData(" + dataId + ")");
                        return null;
                    }
                }, new AntBuildListener() {
                    public void buildFinished(int state, int errorCount) {
                        logger.info("buildFinished(" + state + "," + errorCount + ")");
                    }
                });
                Messages.showInfoMessage("Workspace exported sucessfully.", "Workspace Exported.");
            }
        }
    }
}
